package flwHttpServer

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"queue/facade/frameLog"
	"time"
)

type MsgData struct {
	LogId      string
	host       string
	port       string
	reqData    []byte
	returnCode int
	errMsg     string
	starTime   time.Time
}

func NewHttpSever(host, port string) {
	Mux := http.NewServeMux()
	fmt.Printf("http://%s:%s\n", host, port)
	Mux.HandleFunc("/", index)
	Mux.HandleFunc("/saveMessage", saveMessage)
	serve := http.ListenAndServe(fmt.Sprintf("%s:%s", host, port), Mux)
	if serve != nil {
		frameLog.Warringf("[webServer]start faild! host[%s] port[%s] error info[%s]", host, port, serve.Error())
	}

	/*http.NewServeMux()
	fmt.Printf("http://%s:%s\n",host,port)
	http.HandleFunc("/",index)
	http.HandleFunc("/saveMessage",saveMessage)
	serve := http.ListenAndServe(fmt.Sprintf("%s:%s", host, port), nil)
	if serve != nil {
		tool.Warringf("[webserver]start faild! host[%s] port[%s] error info[%s]",host, port, serve.Error())
	}*/
}

func index(writer http.ResponseWriter, request *http.Request) {
	defer request.Body.Close()
	fmt.Println("hello world !")
	writer.Write([]byte("hello world !"))

}
func saveMessage(writer http.ResponseWriter, request *http.Request) {
	msgData := new(MsgData)
	msgData.starTime = time.Now()
	logId := request.Header.Get("Log-Id")
	msgData.LogId = logId
	msgData.returnCode = 200
	fmt.Println("LogId:", logId)
	if msgData.LogId == "" {
		msgData.returnCode = 500
		msgData.errMsg = "request miss logId"
		fmt.Println("request miss logId")
		response(writer, request, msgData)
		return
	}

	data, err := ioutil.ReadAll(request.Body)
	if err != nil {
		msgData.returnCode = 400
		msgData.errMsg = err.Error()
		frameLog.Errorf("read request err : %s", err)
		response(writer, request, msgData)
		return
	}
	msgData.reqData = data
	fmt.Println(string(data))
	response(writer, request, msgData)
	return
}

func response(writer http.ResponseWriter, req *http.Request, msgData *MsgData) {

	if msgData.returnCode == 200 {
		frameLog.Infof("logId[%s] param[%s]", msgData.LogId, msgData.reqData)

		writer.Write([]byte("success"))
	}
	writer.Write([]byte(msgData.errMsg))

}
